/*
 * MysqlDB.java
 *
 * Created on June 10, 2007, 9:36 PM
 *
 * Copyright 2008 David D. Emory
 * 
 * This file is part of Five Points. See <http://www.fpdev.org> for
 * additional information regarding the project.
 * 
 * Five Points is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Five Points is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Five Points.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.fpdev.core.data;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.fpdev.core.FPEngine;
import org.fpdev.core.DataPackage;
import org.fpdev.util.FPUtil;

/**
 *
 * @author demory
 */
public class LegacyMysqlDB extends LegacyDB {

  /** Creates a new instance of MysqlDB */
  public LegacyMysqlDB(FPEngine engine, DataPackage pkg, String user, String pw) {
    this(engine, pkg, user, pw, null);
  }

  public LegacyMysqlDB(FPEngine engine, DataPackage pkg, String user, String pw, ZipFile zip) {
    super(engine, pkg, user, pw, zip);
  }

  public void init() throws SQLException {
    String url = "jdbc:mysql://localhost/";

    System.out.println("user="+user_);
    System.out.println("pw="+pw_);
    try {
      conn_ = DriverManager.getConnection(url + dataPkg_.getName() + "?autoReconnect=true", user_, pw_);
      System.out.println("Connected to existing MySQL database " +dataPkg_.getName());
      s_ = conn_.createStatement();
      initialized_ = true;
    } catch (SQLException e) {
      initialized_ = createDB(url);
    }
  }
  
  private boolean createDB(String url) {
    try {
      conn_ = DriverManager.getConnection(url, user_, pw_);
      s_ = conn_.createStatement();
      
      s_.executeUpdate("CREATE DATABASE " + dataPkg_.getName());
      s_.executeUpdate("USE " + dataPkg_.getName());
      System.out.println("Created and connected to MySQL database " + dataPkg_.getName());
      
      createBaseNetTables();
      System.out.println("Created tables");
      
      return true;
      
    } catch (SQLException SQLException) {
      System.out.println("Error creating database");
      return false;
    }
    
  }

  public void close() {
    try {
      s_.close();
      System.out.println("Closed result set and statement");
      conn_.close();
    } catch (Throwable e) {
      System.out.println("exception thrown:");
      e.printStackTrace();
    }
  }

  public int getRDBMS() {
    return DB_MYSQL;
  }

  public String jdbcClassname() {
    return "com.mysql.jdbc.Driver";
  }

  public void dumpToZip(ZipOutputStream zos) {
    try {

      String filename = engine_.getProperty("5pHome") + "temp" + File.separator + "mysqldump.sql";
      File file = new File(filename);
      FileWriter fw = null;
      fw = new FileWriter(file);

      String cmd = "mysqldump -u " + user_ + " -p" + pw_ + " " + dataPkg_.getName(); //+" > "+engine_.getProperty("5pHome")+"temp"+File.separator+"mysqldump.sql";
      System.out.println(cmd);
      Process proc = Runtime.getRuntime().exec(cmd);

      //Process child = rt.exec("mysqldump -h"+host+" -u"+user+" -p"+pw+" dump_test");

      InputStream in = proc.getInputStream();
      InputStreamReader isr = new InputStreamReader(in);
      char[] chars = new char[1024];
      int ibyte = 0;
      while ((ibyte = isr.read(chars)) > 0) {
        fw.write(chars);
      }
      fw.close();

      FPUtil.zipFile(filename, zos, "mysql.sql");

    //p.waitFor();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  public void readFromZip(ZipFile zipFile) {
    System.out.println("Reading from zip");
    try {
      String dir = engine_.getProperty("5pHome") + "temp" + File.separator;

      ZipEntry entry = zipFile.getEntry("mysql.sql");

      //System.err.println("Extracting file: " + eName);
      //(new File(dir+"mysql.sql").getParentFile()).mkdirs();
      FPUtil.copyInputStream(zipFile.getInputStream(entry),
              new BufferedOutputStream(new FileOutputStream(dir + "mysql.sql")));

      zipFile.close();

      String cmd = "mysql -u "+user_+" -p"+pw_+" " + engine_.getDataPackage().getName() + " < " + dir + "mysql.sql";
      System.out.println(cmd);
      Process proc = Runtime.getRuntime().exec(cmd);

    //Process child = rt.exec("mysqldump -h"+host+" -u"+user+" -p"+pw+" dump_test");


    //proc.waitFor();

    } catch (Exception ex) {
      ex.printStackTrace();
    }

  }

  public void delete() {
    close();

    String dpName = dataPkg_.getName();
    String url = "jdbc:mysql://localhost/";
    try {
      conn_ = DriverManager.getConnection(url, user_, pw_);
      System.out.println("Connected to existing MySQL database " + dpName);
      s_ = conn_.createStatement();
      s_.execute("DROP DATABASE " + dataPkg_.getName());
      System.out.println("Dropped db " + dataPkg_.getName());
    } catch (SQLException e) {
      e.printStackTrace();
    }

    close();
  }
}
